package com.fosdata.dpm.exception;

import com.fosdata.dpm.entity.dto.ApiResult;
import com.fosdata.dpm.interceptor.NotAssignPermissionException;
import com.fosdata.dpm.interceptor.ParamException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by yhsh on 2021/7/21 11:30
 * version 2.0
 * 方法说明   全局错误处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ApiResult exceptionHandler(Exception e, HttpServletRequest request) {
        LOG.error(e.getMessage(), e);
        if (e instanceof AuthFailedException) {
            return ApiResult.authFailed(e.getMessage());
        }
        if (e instanceof ParamException) {
            return ApiResult.ok(e.getMessage());
        }
        if (e instanceof NotAssignPermissionException) {
            return ApiResult.error("您还没有没有权限，请联系管理员给您分配权限");
        } else if (e instanceof RuntimeException) {
            /**系统运行错误**/
            LOG.error(e.getMessage(), e);
            return ApiResult.error("服务器内部错误");
        } else if (e instanceof BindException) {
            /**如果是绑定的参数错误**/
            BindException exception = (BindException) e;
            return ApiResult.error(exception.getBindingResult().getFieldError().getDefaultMessage());
        } else if (e instanceof Throwable) {
            LOG.error(e.getMessage(), e);
            return ApiResult.error("服务器内部错误");
        }
        return ApiResult.error("服务错误");
    }
}
